#include <QtGui>

#include "calculatorform.h"
#include "unistd.h"



CalculatorForm::CalculatorForm(QWidget *parent)
    : QWidget(parent)
{
  ui.setupUi(this);
  setWindowFlags(Qt::FramelessWindowHint);
}

void CalculatorForm::on_pbOnOff_toggled(bool checked)
{
  int iPort = ui.lePort->text().toInt();
  MyGpioPort.activate_gpio_port(iPort);
  MyGpioPort.set_gpio_value(checked);
  MyGpioPort.desactivate_gpio_port(iPort);
  if(checked)
    ui.pbOnOff->setText("On");
  else
    ui.pbOnOff->setText("Off");
}

void CalculatorForm::on_pbToggle_clicked()
{
  int iPort = ui.lePort->text().toInt();
  int p1 = ui.leDOn->text().toInt();
  int p2 = ui.leDOff->text().toInt();
  int j;
  MyGpioPort.activate_gpio_port(iPort);
  for(int i = 0; i < ui.leStep->text().toInt(); i++)
  {
    j = p1;
    while(j) j--;
    MyGpioPort.set_gpio_value(true);
    j = p2;
    while(j) j--;
    MyGpioPort.set_gpio_value(false);
  }
  MyGpioPort.desactivate_gpio_port(iPort);
}

void CalculatorForm::line(int x, int y, int z)
{
  int cx = 0, cy = 0, cz = 0;
  int bx = x;
  int a0 = 0, a1 = 1, a2 = 2;
  if(y > z && y > x)
  {
    x = y;
    y = bx;
    a0 = 1;
    a1 = 0;
  }

  if(z > y && z > x)
  {
    x = z;
    z = bx;
    a0 = 2;
    a2 = 0;
  }

  int dx =  abs(x), sx = cx<x ? 1 : -1;
  int dy = -abs(y), sy = cy<y ? 1 : -1;
  int dz = -abs(z), sz = cz<z ? 1 : -1;
  int e_xy = dx+dy, e2y;
  int e_xz = dx+dz, e2z;
  ui.teLog->clear();
  while(true)
  {
    qApp->processEvents();
    if (cx==x && cy == y && cz == z) break;
    e2y = 2*e_xy;
    e2z = 2*e_xz;
    if (e2y >= dy) { e_xy += dy; e_xz += dz; cx += sx; step(a0,sx);}
    if (e2y <= dx) { e_xy += dx; cy += sy; step(a1,sy);}
    if (e2z <= dx) { e_xz += dx; cz += sz; step(a2,sz);}
  }
}

void CalculatorForm::on_pbOpen_toggled(bool checked)
{
  if(checked)
  {
    if(!MyGpioPort.open_gpio_port(ui.lePort->text().toInt()))
      return;
    ui.pbOpen->setText("Close");
    ui.pbOnOff->setEnabled(true);
    ui.pbToggle->setEnabled(true);
    ui.leDOff->setEnabled(true);
    ui.leDOn->setEnabled(true);
    ui.leStep->setEnabled(true);
    ui.lePort->setEnabled(false);
  }
  else
  {
    if(!MyGpioPort.close_gpio_port(ui.lePort->text().toInt()))
      return;
    ui.pbOpen->setText("Open");
    ui.pbOnOff->setEnabled(false);
    ui.pbToggle->setEnabled(false);
    ui.leDOff->setEnabled(false);
    ui.leDOn->setEnabled(false);
    ui.leStep->setEnabled(false);
    ui.lePort->setEnabled(true);
  }
}

void CalculatorForm::on_pbMoveTo_clicked()
{
  line(ui.lemx->text().toInt(),
       ui.lemy->text().toInt(),
       ui.lemz->text().toInt());
}

void CalculatorForm::step(int ia, bool id)
{
  ui.teLog->append(QString("%1, %2").arg(ia).arg(id));

  /*int iPort = ui.lePort->text().toInt();
  iPort+=ia;
  MyGpioPort.set_gpio_port(iPort+3,id);

  MyGpioPort.set_gpio_port(iPort,false);
  usleep(ui.leDOff->text().toInt()*100);
  MyGpioPort.set_gpio_port(iPort,true);
  usleep(ui.leDOff->text().toInt()*100);*/
}
